﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;
using System.Web.Script.Serialization;

namespace ConsoleApplication1
{
    class WebUtil
    {
        public static Dictionary<string, string> PostForEntity(string url, string param, Dictionary<string, string> dic = null)
        {
            System.Net.HttpWebRequest request;//仅作展示，这个方法用于发送网络请求可能有性能问题
            request = (System.Net.HttpWebRequest)WebRequest.Create(url);
            // 以POST的方式提交
            request.Method = "POST";
            // 以json的方式提交
            request.ContentType = "application/json;charset=UTF-8";

            // 请求头部
            if (dic != null && dic.Count != 0)
            {
                foreach (var item in dic)
                {
                    request.Headers.Add(item.Key, item.Value);
                }
            }
            byte[] payload;
            // 请求参数
            payload = System.Text.Encoding.UTF8.GetBytes(param);
            request.ContentLength = payload.Length;
            string strValue = "";
            try
            {
                Stream writer = request.GetRequestStream();
                writer.Write(payload, 0, payload.Length);
                writer.Close();
                System.Net.HttpWebResponse response;
                response = (System.Net.HttpWebResponse)request.GetResponse();
                System.IO.Stream s;
                s = response.GetResponseStream();
                string StrDate = "";
                StreamReader Reader = new StreamReader(s, Encoding.UTF8);
                while ((StrDate = Reader.ReadLine()) != null)
                {
                    strValue += StrDate;
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("post请求报错：" + e.Message);
                return null;
            }
            JavaScriptSerializer jss = new JavaScriptSerializer();
            return jss.Deserialize<Dictionary<string, string>>(strValue);
        }
    }
}
